import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';

// 收藏目的地
export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return new NextResponse('Unauthorized', { status: 401 });
    }

    const destination = await prisma.destination.findUnique({
      where: { id: params.id },
      include: {
        savedBy: {
          where: { id: session.user.id }
        }
      }
    });

    if (!destination) {
      return new NextResponse('Destination not found', { status: 404 });
    }

    // 添加收藏关系
    await prisma.user.update({
      where: { id: session.user.id },
      data: {
        savedDestinations: {  // 确保使用正确的字段名
          connect: { id: destination.id }
        }
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Save destination error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
}

// 取消收藏
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return new NextResponse('Unauthorized', { status: 401 });
    }

    const destination = await prisma.destination.findUnique({
      where: { id: params.id }
    });

    if (!destination) {
      return new NextResponse('Destination not found', { status: 404 });
    }

    // 移除收藏关系
    await prisma.user.update({
      where: { id: session.user.id },
      data: {
        savedDestinations: {  // 确保使用正确的字段名
          disconnect: { id: destination.id }
        }
      }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Unsave destination error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
}

// 获取收藏状态
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ saved: false });
    }

    const savedDestination = await prisma.user.findFirst({
      where: {
        id: session.user.id,
        savedDestinations: {
          some: { id: params.id }
        }
      }
    });

    return NextResponse.json({ saved: !!savedDestination });
  } catch (error) {
    console.error('Get save status error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
} 